package tony.web.auth.redis

import tony.core.PROJECT_GROUP
import tony.core.SpringContexts
import tony.core.TOKEN_HEADER_NAME
import tony.core.utils.ifNull
import tony.redis.RedisManager
import tony.web.WebContext
import tony.web.WebSession
import tony.web.exception.UnauthorizedException
import tony.web.utils.headers

/**
 * jwt 实现的session.
 *
 * @author tangli
 * @date 2023/05/25 19:17
 */
public open class RedisWebSession : WebSession {
    public val prefix: String by SpringContexts.Env.getPropertyByLazy(
        "$PROJECT_GROUP.web.auth.redis.prefix",
        "tony:session"
    )

    public val token: String
        get() = WebContext.request.headers[TOKEN_HEADER_NAME].ifNull("")

    override val userId: String
        get() = RedisManager.values.get<String>(prefix + token).ifNull("")

    override val unauthorizedException: UnauthorizedException?
        get() = if (userId.isBlank()) UnauthorizedException("请登录") else null
}
